package io.mqttpush.mqttserver.handles;

import io.mqttpush.mqttserver.config.TopicManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;

import java.util.List;

/**
 * @author tianzhenjiu
 * @date 2020/6/9 17:34
 */
public class UnSubService implements Iservice<MqttUnsubscribeMessage> {

    @Override
    public boolean accept(ChannelHandlerContext context, MqttMessage inMessage) {
        return MqttMessageType.UNSUBSCRIBE==inMessage.fixedHeader().messageType();
    }

    @Override
    public List<Object> service(ChannelHandlerContext context, List<Object> outMessage, MqttUnsubscribeMessage inMessage) {

        outMessage.add(processUnSubscribe(context,inMessage));

        return outMessage;
    }



    /**
     * 处理取消订阅
     * @param context
     * @param unsubscribeMessage
     * @return
     */
    public MqttUnsubAckMessage processUnSubscribe(ChannelHandlerContext context, MqttUnsubscribeMessage unsubscribeMessage){


        List<String> topics = unsubscribeMessage.payload().topics();
        for(String topic:topics ){
            TopicManager.getInstance().unSubscribe(topic,context.channel());
        }


        MqttQoS mqttQoS = unsubscribeMessage.fixedHeader().qosLevel();
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBACK, false, mqttQoS, false, 0);
        MqttUnsubAckMessage unsubAckMessage=new MqttUnsubAckMessage(fixedHeader, MqttMessageIdVariableHeader.from(unsubscribeMessage.variableHeader().messageId()));

        return unsubAckMessage;
    }
}
